package com.epam.grsulab.webapi.web.app;

import javax.servlet.ServletContext;

import org.apache.wicket.Page;
import org.apache.wicket.protocol.http.WebApplication;
import org.apache.wicket.spring.injection.annot.SpringComponentInjector;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.epam.grsulab.webapi.tools.DataInitialiser;
import com.epam.grsulab.webapi.web.pages.data.DataViewPage;

/**
 * @author Dmitry_Zhivushko
 * 
 */
public abstract class WicketApplication extends WebApplication {

	private ApplicationContext applicationContext;
	private DataInitialiser dataInitializer;

	/**
	 * Constructor
	 */
	public WicketApplication() {
	}

	protected SpringComponentInjector getSpringInjector() {
		return new SpringComponentInjector(this);
	}

	@Override
	protected void init() {
		super.init();
		addComponentInstantiationListener(getSpringInjector());
		

		// init data on startup
		try {
			dataInitializer = getApplicationContext().getBean(DataInitialiser.class);
			dataInitializer.initData();
			mountBookmarkablePage("database", DataViewPage.class);
		} catch (NoSuchBeanDefinitionException e) {
			// noting to do
		}
	}

	@Override
	public abstract Class<? extends Page> getHomePage();

	/**
	 * Internal initialization overriding for possibility of Spring framework
	 * using.
	 */
	@Override
	protected void internalInit() {
		super.internalInit();

		if (applicationContext == null) {
			// this application was not created as a spring bean so we
			// locate the app context from servlet context

			final ServletContext sc = getServletContext();
			applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
		}
	}

	public ApplicationContext getApplicationContext() {
		return applicationContext;
	}
}
